import React, { useEffect, useState } from 'react'
import Stats from 'stats.js'

import UPlot from './uplot'

import dataSource from '../../data-source'

function ChartPage() {
  const [metadata, setMetadata] = useState({
    timestamp: null,
    fromCache: false
  })
  const [chartList, setChartList] = useState([])

  useEffect(() => {
    const stats = new Stats()
    stats.showPanel(0)
    document.body.appendChild(stats.dom)

    dataSource.on('updateChartData', data => {
      stats.begin()

      setMetadata({
        timestamp: data.timestamp,
        fromCache: data.fromCache
      })
      setChartList(data.data[0])

      stats.end()
    })

    window.addEventListener('click', () => {
      dataSource.togglePlayer()
    })
  }, [])

  return pug`
    div
      div #{metadata.timestamp}
      div #{metadata.fromCache ? 'USEING CACHE' : 'NO USE'}
      .box.box-wrap
        each item, index in chartList
          UPlot(series=item.series id=item.title key=item.title)
  `
}

export default ChartPage
